package com.inno.life.domain.sensitive;

import com.github.houbb.sensitive.word.api.IWordDeny;
import com.inno.life.infra.basic.entity.PlannerMomentSensitiveWords;
import com.inno.life.infra.basic.service.PlannerMomentSensitiveWordsService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author sean
 * 敏感词自定义词库
 */
@Slf4j
@Component
public class MyWordDeny implements IWordDeny {
    @Resource
    private PlannerMomentSensitiveWordsService plannerMomentSensitiveWordsService;
    private final static ExecutorService SENSITIVE_POOL = Executors.newFixedThreadPool(5);

    private static final int PAGE_SIZE = 1000;
    private final AtomicInteger startIndex = new AtomicInteger(0);
    @Override
    public List<String> deny() {
        long totalCount = plannerMomentSensitiveWordsService.count(null);
        long queryCount = (totalCount / PAGE_SIZE) + 1;
        List<Future<List<PlannerMomentSensitiveWords>>> futures = new ArrayList<>();
        for (long l = 0; l < queryCount; l++) {
            futures.add(SENSITIVE_POOL.submit(
                    ()-> {
                        List<PlannerMomentSensitiveWords> words = this.plannerMomentSensitiveWordsService.queryAllByLimit(startIndex.getAndIncrement(), PAGE_SIZE);
                        log.debug("sensitive words loading:{}", words);
                        return words;
                    })
            );
        }

        List<PlannerMomentSensitiveWords> wordsList = new ArrayList<>();
        for (Future<List<PlannerMomentSensitiveWords>> future : futures) {
            try {
                wordsList.addAll(future.get());
                if (log.isInfoEnabled()){
                    log.info("sensitive words initialize:{}", wordsList);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return wordsList.stream()
                .map(PlannerMomentSensitiveWords::getContent)
                .toList();
    }
}
